<!-- src/components/UserModal.vue -->
<template>
  <div class="modal-overlay" @click.self="close">
    <div class="modal-content">
      <div class="modal-header">
        <h3>{{ isEditing ? '编辑用户' : '添加用户' }}</h3>
        <button class="close-btn" @click="close">×</button>
      </div>

      <form @submit.prevent="submitForm">
        <div class="form-grid">
          <div class="form-group">
            <label>用户名 *</label>
            <input 
              v-model="formData.username" 
              required 
              placeholder="输入用户名"
              :disabled="isEditing"
            >
          </div>

          <div class="form-group">
            <label>邮箱</label>
            <input 
              v-model="formData.email" 
              type="email" 
              placeholder="输入邮箱地址"
            >
          </div>

          <div class="form-group">
            <label>手机号</label>
            <input 
              v-model="formData.phone" 
              placeholder="输入手机号"
            >
          </div>

          <div class="form-group">
            <label>状态</label>
            <select v-model="formData.status">
              <option :value="1">启用</option>
              <option :value="0">禁用</option>
            </select>
          </div>

          <div v-if="!isEditing" class="form-group">
            <label>密码 *</label>
            <input 
              v-model="formData.password" 
              type="password" 
              required 
              placeholder="输入密码"
            >
          </div>

          <div v-if="!isEditing" class="form-group">
            <label>确认密码 *</label>
            <input 
              v-model="formData.confirmPassword" 
              type="password" 
              required 
              placeholder="确认密码"
            >
          </div>

          <div class="form-group full-width">
            <label>角色</label>
            <select v-model="formData.role">
              <option value="">请选择角色</option>
              <option value="admin">管理员</option>
              <option value="teacher">教师</option>
              <option value="student">学生</option>
            </select>
          </div>
        </div>

        <div class="modal-actions">
          <button type="button" class="btn-cancel" @click="close">取消</button>
          <button type="submit" class="btn-submit" :disabled="loading">
            {{ loading ? '保存中...' : (isEditing ? '更新' : '创建') }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
import { ref, computed, watch } from 'vue';
import { userApi } from '@/api/user';
import { LoginRequest, RegisterRequest } from '@/models/user';

export default {
  name: 'UserModal',
  props: {
    user: {
      type: Object,
      default: null
    }
  },
  emits: ['close', 'saved'],
  setup(props, { emit }) {
    const loading = ref(false);
    const isEditing = computed(() => !!props.user);
    
    // 使用LoginRequest格式的表单数据
    const formData = ref(new LoginRequest());

    // 先定义resetForm函数
    const resetForm = () => {
      formData.value = new LoginRequest();
    };

    // 使用watch监听props变化
    watch(() => props.user, (newUser) => {
      if (newUser) {
        formData.value = new LoginRequest(
          newUser.username,
          '', // 密码不显示
          newUser.email,
          newUser.phone,
          newUser.status
        );
      } else {
        resetForm();
      }
    }, { immediate: true });

    const close = () => {
      emit('close');
    };

    const submitForm = async () => {
      // 表单验证
      if (!formData.value.username.trim()) {
        alert('请输入用户名');
        return;
      }
      if (!isEditing.value && !formData.value.password) {
        alert('请输入密码');
        return;
      }
      if (!isEditing.value && formData.value.password !== formData.value.confirmPassword) {
        alert('两次输入的密码不一致');
        return;
      }
      if (!isEditing.value && formData.value.password.length < 6) {
        alert('密码长度不能少于6位');
        return;
      }

      loading.value = true;
      try {
        if (isEditing.value) {
          // 编辑用户 - 使用LoginRequest格式
          const submitData = new LoginRequest(
            formData.value.username,
            formData.value.password || undefined, // 如果不修改密码，不传递
            formData.value.email,
            formData.value.phone,
            formData.value.status
          );
          
          console.log('📝 编辑用户提交数据:', submitData);
          const response = await userApi.updateUser(props.user.id, submitData);
          
          if (response.data.code === '000000') {
            emit('saved');
          } else {
            throw new Error(response.data.msg);
          }
        } else {
          // 新增用户 - 使用RegisterRequest格式（需要补充role字段）
          const submitData = new RegisterRequest(
            formData.value.username,
            formData.value.password,
            formData.value.email,
            formData.value.phone,
            formData.value.role
          );
          
          console.log('➕ 新增用户提交数据:', submitData);
          const response = await userApi.registerUser(submitData);
          
          if (response.data.code === '000000') {
            emit('saved');
          } else {
            throw new Error(response.data.msg);
          }
        }
      } catch (error) {
        console.error('保存用户失败:', error);
        const errorMsg = error.response?.data?.message || error.message || '操作失败';
        alert(`操作失败: ${errorMsg}`);
      } finally {
        loading.value = false;
      }
    };

    return {
      formData,
      isEditing,
      loading,
      close,
      submitForm
    };
  }
};
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 600px;
  max-width: 90vw;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.close-btn:hover {
  color: #666;
}

.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  padding: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group.full-width {
  grid-column: 1 / -1;
}

.form-group label {
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.form-group input,
.form-group select {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-group input:focus,
.form-group select:focus {
  outline: none;
  border-color: #3498db;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px;
  border-top: 1px solid #eee;
}

.btn-cancel, .btn-submit {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.btn-cancel {
  background: #f5f5f5;
  color: #666;
}

.btn-submit {
  background: #3498db;
  color: white;
}

.btn-submit:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.btn-submit:hover:not(:disabled) {
  background: #2980b9;
}
</style>